package stack;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * 支持自动扩容的栈
 * @param <E>
 */
public class ResizingArrayStack<E> implements Iterable<E> {

    private static int CAPACITY = 1;

    //数组
    private E[] elements ;
    //元素个数
    private int number = 0;

    public ResizingArrayStack() {
        this(CAPACITY);
    }

    public ResizingArrayStack(int capacity){
        elements = (E[]) new Object[capacity];
    }

    public boolean isEmpty() {
        return number == 0;
    }

    public int size() {
        return number;
    }

    public void push(E e) {
        if (number == elements.length) {
            resize(number * 2);
        }
        elements[number++] = e;
    }

    public E pop() {
        E e = elements[--number];
        elements[number] = null; //help GC
        if (number <= elements.length >> 2) {
            resize(elements.length >> 1);
        }
        return e;
    }

    private void resize(int newSize) {
        if (newSize >= Integer.MAX_VALUE) {
            return;
        }
        E[] newEles = (E[]) new Object[newSize];
        for (int i = 0; i < elements.length; i++) {
            newEles[i] = elements[i];
        }
        elements = newEles;
    }


    @Override
    public Iterator<E> iterator() {
        return new Ite();
    }

    @Override
    public void forEach(Consumer<? super E> action) {

    }

    @Override
    public Spliterator<E> spliterator() {
        return null;
    }

    class Ite implements Iterator<E> {

        private int i = number;
        @Override
        public boolean hasNext() {
            return number > 0;
        }

        @Override
        public E next() {
            return elements[--i];
        }
    }
}
